import { useState } from 'react';
import {
  Tabs,
  Upload,
  Button,
  message,
  Card,
  Form,
  InputNumber,
  List,
  Typography,
  Space,
  Alert,
  Spin,
  Row,
  Col,
  Slider,
  Divider,
  Modal,
  Checkbox
} from 'antd';
import {
  UploadOutlined,
  FileOutlined,
  AudioOutlined,
  VideoCameraOutlined,
  LinkOutlined,
  CodeOutlined,
  PlayCircleOutlined,
  FileImageOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';
import { processVideo, generateWebEffects, generateVideoEffects, downloadEffectsAsZip } from '../services/api';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;

type FileType = {
  name: string;
  url: string;
  type: string;
};

type EffectType = {
  id: string;
  url: string;
  opacity: string;
  type: string;
};

const VideoProcess = () => {
  const [uploading, setUploading] = useState(false);
  const [processingResult, setProcessingResult] = useState<{
    mp3?: string;
    silentVideo?: string;
    wavSegments?: string[];
  } | null>(null);

  // 生成特效相关状态
  const [generatingWebEffects, setGeneratingWebEffects] = useState(false);
  const [generatingVideoEffects, setGeneratingVideoEffects] = useState(false);
  const [webEffects, setWebEffects] = useState<EffectType[]>([]);
  const [videoEffects, setVideoEffects] = useState<EffectType[]>([]);
  const [effectUrls, setEffectUrls] = useState<string[]>([]);
  const [videoEffectUrls, setVideoEffectUrls] = useState<string[]>([]);

  // 添加多选状态
  const [selectedWebEffects, setSelectedWebEffects] = useState<string[]>([]);
  const [selectedVideoEffects, setSelectedVideoEffects] = useState<string[]>([]);

  // 添加视频处理结果选择状态
  const [selectedProcessResults, setSelectedProcessResults] = useState<string[]>([]);

  // 上传前检查文件类型和大小
  const beforeUpload = (file: File) => {
    const isMP4 = file.type === 'video/mp4';
    const isLessThan1GB = file.size / 1024 / 1024 / 1024 < 1;

    if (!isMP4) {
      message.error('只能上传MP4格式的视频文件!');
      return Upload.LIST_IGNORE;
    }

    if (!isLessThan1GB) {
      message.error('视频文件大小不能超过1GB!');
      return Upload.LIST_IGNORE;
    }

    return true;
  };

  // 自定义上传
  const customUpload = async (options: any) => {
    const { file, onSuccess, onError, onProgress } = options;

    // 创建FormData
    const formData = new FormData();
    formData.append('video', file);

    try {
      setUploading(true);

      // 进度处理函数
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: (progressEvent: any) => {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          onProgress({ percent: percentCompleted });
        },
        timeout: 300000, // 5分钟超时
      };

      // 使用axios直接调用，方便处理进度
      const response = await processVideo(file);
      const { success, data } = response.data;

      if (success) {
        setProcessingResult(data);
        message.success('视频处理成功');
        onSuccess('OK');
      } else {
        message.error('视频处理失败');
        onError('处理失败');
      }
    } catch (error: any) {
      console.error('视频处理出错:', error);

      // 更详细的错误信息
      if (error.response) {
        // 服务器返回了错误响应
        const errorMsg = error.response.data?.message || '服务器返回错误';
        message.error(`上传失败: ${errorMsg}`);
      } else if (error.request) {
        // 请求已发送但未收到响应
        message.error('上传超时或服务器未响应，请检查网络或稍后重试');
      } else {
        // 请求设置时出错
        message.error(`上传出错: ${error.message}`);
      }

      onError('上传出错');
    } finally {
      setUploading(false);
    }
  };

  // 生成网页特效
  const handleGenerateWebEffects = async ({ count }: { count: number }) => {
    try {
      setGeneratingWebEffects(true);
      const response = await generateWebEffects(count || 3);
      console.log('response', response);
      if (response.data && response.data.data.effects) {
        const urls = response.data.data.effects.map((effect: any) => effect.url);
        console.log('urls', urls);
        setEffectUrls(urls);
        setWebEffects(response.data.data.effects);
        message.success(`成功生成${urls.length}个网页特效`);
      }
      setGeneratingWebEffects(false);
    } catch (error) {
      console.error('生成网页特效出错:', error);
      message.error('生成网页特效失败');
      setGeneratingWebEffects(false);
    }
  };

  // 生成视频特效
  const handleGenerateVideoEffects = async ({ count }: { count: number }) => {
    try {
      setGeneratingVideoEffects(true);
      const response = await generateVideoEffects(count || 2);
      if (response.data && response.data.data.effects) {
        const urls = response.data.data.effects.map((effect: any) => effect.url);
        setVideoEffectUrls(urls);
        setVideoEffects(response.data.data.effects);
        message.success(`成功生成${urls.length}个视频特效`);
      }
      setGeneratingVideoEffects(false);
    } catch (error) {
      console.error('生成视频特效出错:', error);
      message.error('生成视频特效失败');
      setGeneratingVideoEffects(false);
    }
  };

  // 下载网页特效为ZIP
  const handleDownloadWebEffectsAsZip = async () => {
    if (effectUrls.length === 0) {
      Modal.warning({
        title: '没有可下载的特效',
        content: '请先生成网页特效，然后再尝试批量下载。',
      });
      return;
    }

    try {
      message.loading({ content: '正在准备下载...', key: 'webDownload' });
      const response = await downloadEffectsAsZip(effectUrls, 'web');
      console.log('response', response);
      if (response.data && response.data.data.downloadUrl) {
        window.open(response.data.data.downloadUrl, '_blank');
        message.success({ content: '下载已开始', key: 'webDownload' });
      } else {
        message.error({ content: '下载失败', key: 'webDownload' });
      }
    } catch (error) {
      console.error('下载特效出错:', error);
      message.error({ content: '下载特效失败', key: 'webDownload' });
    }
  };

  // 下载视频特效为ZIP
  const handleDownloadVideoEffectsAsZip = async () => {
    if (videoEffectUrls.length === 0) {
      Modal.warning({
        title: '没有可下载的特效',
        content: '请先生成视频特效，然后再尝试批量下载。',
      });
      return;
    }

    try {
      message.loading({ content: '正在准备下载...', key: 'videoDownload' });
      const response = await downloadEffectsAsZip(videoEffectUrls, 'video');
      if (response.data && response.data.data.downloadUrl) {
        window.open(response.data.data.downloadUrl, '_blank');
        message.success({ content: '下载已开始', key: 'videoDownload' });
      } else {
        message.error({ content: '下载失败', key: 'videoDownload' });
      }
    } catch (error) {
      console.error('下载特效出错:', error);
      message.error({ content: '下载特效失败', key: 'videoDownload' });
    }
  };

  // 处理网页特效选择
  const handleWebEffectSelect = (url: string, checked: boolean) => {
    if (checked) {
      setSelectedWebEffects([...selectedWebEffects, url]);
    } else {
      setSelectedWebEffects(selectedWebEffects.filter(item => item !== url));
    }
  };

  // 处理视频特效选择
  const handleVideoEffectSelect = (url: string, checked: boolean) => {
    if (checked) {
      setSelectedVideoEffects([...selectedVideoEffects, url]);
    } else {
      setSelectedVideoEffects(selectedVideoEffects.filter(item => item !== url));
    }
  };

  // 下载选中的网页特效
  const handleDownloadSelectedWebEffects = async () => {
    if (selectedWebEffects.length === 0) {
      Modal.warning({
        title: '没有选中的特效',
        content: '请先选择要下载的网页特效，然后再尝试下载。',
      });
      return;
    }

    try {
      message.loading({ content: '正在准备下载...', key: 'selectedWebDownload' });
      const response = await downloadEffectsAsZip(selectedWebEffects, 'web');
      if (response.data && response.data.data.downloadUrl) {
        window.open(response.data.data.downloadUrl, '_blank');
        message.success({ content: '下载已开始', key: 'selectedWebDownload' });
      } else {
        message.error({ content: '下载失败', key: 'selectedWebDownload' });
      }
    } catch (error) {
      console.error('下载特效出错:', error);
      message.error({ content: '下载特效失败', key: 'selectedWebDownload' });
    }
  };

  // 下载选中的视频特效
  const handleDownloadSelectedVideoEffects = async () => {
    if (selectedVideoEffects.length === 0) {
      Modal.warning({
        title: '没有选中的特效',
        content: '请先选择要下载的视频特效，然后再尝试下载。',
      });
      return;
    }

    try {
      message.loading({ content: '正在准备下载...', key: 'selectedVideoDownload' });
      const response = await downloadEffectsAsZip(selectedVideoEffects, 'video');
      if (response.data && response.data.data.downloadUrl) {
        window.open(response.data.data.downloadUrl, '_blank');
        message.success({ content: '下载已开始', key: 'selectedVideoDownload' });
      } else {
        message.error({ content: '下载失败', key: 'selectedVideoDownload' });
      }
    } catch (error) {
      console.error('下载特效出错:', error);
      message.error({ content: '下载特效失败', key: 'selectedVideoDownload' });
    }
  };

  // 处理视频处理结果选择
  const handleProcessResultSelect = (url: string, checked: boolean) => {
    if (checked) {
      setSelectedProcessResults([...selectedProcessResults, url]);
    } else {
      setSelectedProcessResults(selectedProcessResults.filter(item => item !== url));
    }
  };

  // 下载选中的视频处理结果
  const handleDownloadSelectedProcessResults = async () => {
    if (selectedProcessResults.length === 0) {
      Modal.warning({
        title: '没有选中的文件',
        content: '请先选择要下载的文件，然后再尝试下载。',
      });
      return;
    }

    try {
      message.loading({ content: '正在准备下载...', key: 'selectedProcessDownload' });
      const response = await downloadEffectsAsZip(selectedProcessResults, 'process');
      if (response.data && response.data.data.downloadUrl) {
        window.open(response.data.data.downloadUrl, '_blank');
        message.success({ content: '下载已开始', key: 'selectedProcessDownload' });
      } else {
        message.error({ content: '下载失败', key: 'selectedProcessDownload' });
      }
    } catch (error) {
      console.error('下载文件出错:', error);
      message.error({ content: '下载文件失败', key: 'selectedProcessDownload' });
    }
  };

  // 下载所有视频处理结果
  const handleDownloadAllProcessResults = async () => {
    if (!processingResult) {
      return;
    }

    const allUrls = [
      processingResult.mp3 || '',
      processingResult.silentVideo || '',
      ...(processingResult.wavSegments || [])
    ].filter(url => url); // 过滤掉空URL

    if (allUrls.length === 0) {
      Modal.warning({
        title: '没有可下载的文件',
        content: '处理结果中没有可下载的文件。',
      });
      return;
    }

    try {
      message.loading({ content: '正在准备下载...', key: 'allProcessDownload' });
      const response = await downloadEffectsAsZip(allUrls, 'process');
      if (response.data && response.data.data.downloadUrl) {
        window.open(response.data.data.downloadUrl, '_blank');
        message.success({ content: '下载已开始', key: 'allProcessDownload' });
      } else {
        message.error({ content: '下载失败', key: 'allProcessDownload' });
      }
    } catch (error) {
      console.error('下载文件出错:', error);
      message.error({ content: '下载文件失败', key: 'allProcessDownload' });
    }
  };

  // 打开文件
  const openFile = (url: string) => {
    window.open(url, '_blank');
  };

  return (
    <div className="video-process-container">
      <Title level={2}>视频处理中心</Title>
      <Tabs defaultActiveKey="1">
        <TabPane
          tab={<span><VideoCameraOutlined />视频处理</span>}
          key="1"
        >
          <Card title="上传视频">
            <Alert
              message="功能说明"
              description="上传MP4视频文件，系统将自动提取音频为MP3，同时生成无声视频，并将MP3切割为多个WAV片段。"
              type="info"
              showIcon
              style={{ marginBottom: 20 }}
            />
            <Upload
              name="video"
              beforeUpload={beforeUpload}
              customRequest={customUpload}
              maxCount={1}
              showUploadList={{
                showRemoveIcon: true,
                showDownloadIcon: false
              }}
              progress={{
                strokeColor: {
                  '0%': '#108ee9',
                  '100%': '#87d068',
                },
                strokeWidth: 3,
                format: (percent) => `${percent ? Math.round(percent) : 0}%`,
              }}
              accept=".mp4"
            >
              <Button
                icon={<UploadOutlined />}
                loading={uploading}
                type="primary"
                disabled={uploading}
              >
                {uploading ? '处理中...' : '选择MP4视频文件'}
              </Button>
              {uploading && (
                <div style={{ marginTop: 12, color: '#999' }}>
                  处理大文件需要较长时间，请耐心等待...
                </div>
              )}
            </Upload>
          </Card>

          {processingResult && (
            <Card 
              title="处理结果" 
              style={{ marginTop: 16 }}
              extra={
                <Space>
                  <Button 
                    type="primary" 
                    icon={<DownloadOutlined />} 
                    onClick={handleDownloadAllProcessResults}
                  >
                    全部下载
                  </Button>
                  <Button 
                    type="primary" 
                    icon={<DownloadOutlined />} 
                    onClick={handleDownloadSelectedProcessResults}
                    disabled={selectedProcessResults.length === 0}
                  >
                    下载所选 ({selectedProcessResults.length})
                  </Button>
                </Space>
              }
            >
              <List
                bordered
                dataSource={[
                  {
                    name: '提取的MP3音频',
                    url: processingResult.mp3 || '',
                    type: 'audio'
                  },
                  {
                    name: '无声视频',
                    url: processingResult.silentVideo || '',
                    type: 'video'
                  },
                  ...(processingResult.wavSegments?.map((url, index) => ({
                    name: `WAV音频片段 ${index + 1}`,
                    url,
                    type: 'audio'
                  })) || [])
                ]}
                renderItem={(item: FileType) => (
                  <List.Item
                    actions={[
                      <Button
                        key="download"
                        type="link"
                        onClick={() => openFile(item.url)}
                        icon={<LinkOutlined />}
                      >
                        打开
                      </Button>
                    ]}
                  >
                    <Checkbox 
                      checked={selectedProcessResults.includes(item.url)}
                      onChange={(e) => handleProcessResultSelect(item.url, e.target.checked)}
                      disabled={!item.url}
                    />
                    <List.Item.Meta
                      avatar={
                        item.type === 'audio' ?
                          <AudioOutlined style={{ fontSize: 24, color: '#1677ff' }} /> :
                          <VideoCameraOutlined style={{ fontSize: 24, color: '#52c41a' }} />
                      }
                      title={item.name}
                      description={item.url}
                    />
                  </List.Item>
                )}
              />
            </Card>
          )}
        </TabPane>

        <TabPane
          tab={<span><CodeOutlined />网页特效</span>}
          key="2"
        >
          <Card title="生成网页特效">
            <Alert
              message="功能说明"
              description="生成指定数量的随机网页特效HTML，透明度为0.01-0.10。"
              type="info"
              showIcon
              style={{ marginBottom: 20 }}
            />
            <Form
              name="webEffects"
              layout="inline"
              onFinish={handleGenerateWebEffects}
              initialValues={{ count: 3 }}
            >
              <Form.Item
                name="count"
                label="生成数量"
                rules={[
                  { required: true, message: '请输入数量' },
                  { type: 'number', min: 1, max: 20, message: '数量范围为1-20' }
                ]}
              >
                <InputNumber min={1} max={20} />
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={generatingWebEffects}
                >
                  生成特效
                </Button>
              </Form.Item>
            </Form>
          </Card>

          {webEffects.length > 0 && (
            <Card 
              title="网页特效列表" 
              style={{ marginTop: 16 }}
              extra={
                <Space>
                  <Button 
                    type="primary" 
                    icon={<DownloadOutlined />} 
                    onClick={handleDownloadWebEffectsAsZip}
                  >
                    全部下载
                  </Button>
                  <Button 
                    type="primary" 
                    icon={<DownloadOutlined />} 
                    onClick={handleDownloadSelectedWebEffects}
                    disabled={selectedWebEffects.length === 0}
                  >
                    下载所选 ({selectedWebEffects.length})
                  </Button>
                </Space>
              }
            >
              <List
                bordered
                dataSource={webEffects}
                renderItem={(item: EffectType) => (
                  <List.Item
                    actions={[
                      <Button
                        key="preview"
                        type="link"
                        onClick={() => openFile(item.url)}
                        icon={<LinkOutlined />}
                      >
                        预览
                      </Button>
                    ]}
                  >
                    <Checkbox 
                      checked={selectedWebEffects.includes(item.url)}
                      onChange={(e) => handleWebEffectSelect(item.url, e.target.checked)}
                    />
                    <List.Item.Meta
                      avatar={<CodeOutlined style={{ fontSize: 24, color: '#722ed1' }} />}
                      title={`特效 ${item.id.substring(0, 8)}`}
                      description={
                        <Space direction="vertical">
                          <Text>类型: {item.type}</Text>
                          <Text>透明度: {item.opacity}</Text>
                          <Text type="secondary">{item.url}</Text>
                        </Space>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          )}
        </TabPane>

        <TabPane
          tab={<span><PlayCircleOutlined />视频特效</span>}
          key="3"
        >
          <Card title="生成视频特效">
            <Alert
              message="功能说明"
              description="生成指定数量的随机视频特效MP4，透明度为0.01-0.10。"
              type="info"
              showIcon
              style={{ marginBottom: 20 }}
            />
            <Form
              name="videoEffects"
              layout="inline"
              onFinish={handleGenerateVideoEffects}
              initialValues={{ count: 2 }}
            >
              <Form.Item
                name="count"
                label="生成数量"
                rules={[
                  { required: true, message: '请输入数量' },
                  { type: 'number', min: 1, max: 10, message: '数量范围为1-10' }
                ]}
              >
                <InputNumber min={1} max={10} />
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={generatingVideoEffects}
                >
                  生成特效
                </Button>
              </Form.Item>
            </Form>
            {generatingVideoEffects && (
              <div style={{ marginTop: 16, textAlign: 'center' }}>
                <Spin tip="生成中...这可能需要一些时间" />
                <Paragraph style={{ marginTop: 8 }}>
                  视频特效生成需要较长时间，请耐心等待
                </Paragraph>
              </div>
            )}
          </Card>

          {videoEffects.length > 0 && (
            <Card 
              title="视频特效列表" 
              style={{ marginTop: 16 }}
              extra={
                <Space>
                  <Button 
                    type="primary" 
                    icon={<DownloadOutlined />} 
                    onClick={handleDownloadVideoEffectsAsZip}
                  >
                    全部下载
                  </Button>
                  <Button 
                    type="primary" 
                    icon={<DownloadOutlined />} 
                    onClick={handleDownloadSelectedVideoEffects}
                    disabled={selectedVideoEffects.length === 0}
                  >
                    下载所选 ({selectedVideoEffects.length})
                  </Button>
                </Space>
              }
            >
              <List
                bordered
                dataSource={videoEffects}
                renderItem={(item: EffectType) => (
                  <List.Item
                    actions={[
                      <Button
                        key="preview"
                        type="link"
                        onClick={() => openFile(item.url)}
                        icon={<LinkOutlined />}
                      >
                        预览
                      </Button>
                    ]}
                  >
                    <Checkbox 
                      checked={selectedVideoEffects.includes(item.url)}
                      onChange={(e) => handleVideoEffectSelect(item.url, e.target.checked)}
                    />
                    <List.Item.Meta
                      avatar={<PlayCircleOutlined style={{ fontSize: 24, color: '#f5222d' }} />}
                      title={`特效 ${item.id.substring(0, 8)}`}
                      description={
                        <Space direction="vertical">
                          <Text>类型: {item.type}</Text>
                          <Text>透明度: {item.opacity}</Text>
                          <Text type="secondary">{item.url}</Text>
                        </Space>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          )}
        </TabPane>
      </Tabs>
    </div>
  );
};

export default VideoProcess; 